package com.kk.springboot_001.service;

import com.kk.springboot_001.mapper.LoginMapper;
import com.kk.springboot_001.pojo.User;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private LoginMapper loginMapper;

    /**
     * 根据用户名查询用户信息
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("用户名：{}", username);
        User user = loginMapper.selectUserByName(username);
        if (user == null) {
            log.info("用户不存在");
            throw new UsernameNotFoundException("用户不存在");
        }
        log.info("用户：{}", user);
        return org.springframework.security.core.userdetails.User.builder()
                .username(user.getUserName())
                .password(user.getPassword())
                .roles("USER")
                .build();
    }
}
